package com.routz.nettydemo.customprotocol.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ChickenClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        byte[] d = new byte[60];
        byte[] b = new byte[620];
        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("F:/data.txt")));
                ByteArrayOutputStream baos = new ByteArrayOutputStream(680)) {
            bis.read(d, 0, 60);
            bis.read(b, 0, 620);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Client active");
        while(true) {
            ctx.writeAndFlush(Unpooled.copiedBuffer(d));
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer(b));
        }
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx,
                             io.netty.buffer.ByteBuf in) {
        System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
